<!--
 * @Author: cqg 
 * @Date: 2020-11-16 08:59:41
 * @LastEditors: cqg
 * @LastEditTime: 2020-12-31 00:10:45
 * @Description: file content
-->
<template>
  <div>
    <el-dialog title="核算" :visible.sync="dialogTableVisible" width="85%" :close-on-click-modal="false">
      <div v-loading="reviewLoading" element-loading-text="正在复核中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
        <div style="width: 100%; height: 450px;overflow-y: scroll;">
          <h2 style="text-align: center;">福田物管中心租赁社会物业租金核算表</h2>
          <h3>一、合同收款汇总信息</h3>
          <table class="table" border="1" cellspacing="0" cellpadding="15">
            <tbody>
              <tr>
                <th>承租方</th>
                <td colspan="5">{{ form.rentContract.customerName }}</td>
              </tr>
              <tr>
                <th>物业名称</th>
                <td colspan="5">{{ form.rentContract.propertyNames }}</td>
              </tr>
              <tr>
                <th>物业地址</th>
                <td colspan="5">{{ form.rentContract.address }}</td>
              </tr>
              <tr>
                <th>面积(m²)</th>
                <td colspan="5">{{ form.rentContract.buildingArea }}</td>
              </tr>
              <tr>
                <th>合同期限</th>
                <td colspan="5">
                  {{ form.rentContract.startDate }}-{{
                  form.rentContract.endDate
                  }}
                </td>
              </tr>
              <tr>
                <th>合同总租金(元)</th>
                <td colspan="5">{{ form.contractReceivableMoneyTotal }}</td>
              </tr>
              <tr>
                <th>合同累计已收金额(元)</th>
                <td colspan="5">{{ form.contractActualMoneyTotal }}</td>
              </tr>
              <tr>
                <th align="center">历史欠款总金额(元)</th>
                <td colspan="5">{{ form.historyArrearsTotal }}</td>
              </tr>
              <tr>
                <th>合同租金余额(元)</th>
                <td colspan="5">{{ form.contractArrearsTotal }}</td>
              </tr>
            </tbody>
          </table>
          <h3>二、本次待收款明细</h3>

          <el-table ref="multipleTable" :data="form.collectionBillDetails" style="width: 100%" @select="check" @selection-change="handleSelectionChange">
            <el-table-column type="selection" v-if="type == 'edit'" width="55" prop="checked">
              <template slot-scope="scope">
                <el-checkbox @change="check" v-model="scope.row.checked"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="chargeProjectName" label="费用科目" width="auto"></el-table-column>
            <el-table-column prop="address" label="费用所属周期">
              <template slot-scope="scope">
                {{ scope.row.costPeriodStart }}-{{
                scope.row.costPeriodEnd
                }}
              </template>
            </el-table-column>
            <el-table-column prop="receivableDate" label="应收日期"></el-table-column>
            <el-table-column prop="receivableMoneyOld" label="合同金额
  (元)"></el-table-column>
            <el-table-column prop="adjustmentAmount" label="累计缴费
  调整金额(元)"></el-table-column>
            <el-table-column prop="receivableMoney" label="应收金额
  (元)"></el-table-column>
            <el-table-column prop="actualAmount" label="已收金额
  (元)"></el-table-column>
            <el-table-column prop="arrears" label="待收金额
  (元)"></el-table-column>
            <el-table-column prop="billAmount" label="本次申请
  收款金额(元)">
              <template slot-scope="scope">
                <span v-if="type !== 'edit'">{{ scope.row.billAmount }}</span>
                <el-input v-else @change="CheckApplicationAmount()" v-model.number="scope.row.billAmount" placeholder="请输入"></el-input>
              </template>
            </el-table-column>
          </el-table>

          <h3>三、本次收款汇总信息</h3>

          <table class="table" border="1" cellspacing="0" cellpadding="15">
            <tbody>
              <tr>
                <th>本次合同金额(元)</th>
                <td>{{ form.currentContractReceivableMoney }}</td>
                <th>本次待收金额(元)</th>
                <td>{{ form.currentReceivableMoney }}</td>
              </tr>
              <tr></tr>
              <tr>
                <th align="center">应收调整(元)</th>
                <td>{{ form.currentAdjustmentMoney }}</td>
                <th>本次申请收款金额(元)</th>
                <td colspan="3">{{ form.receivableTotal }}</td>
              </tr>
              <tr></tr>
              <tr>
                <th>本次收款所属周期</th>
                <td colspan="3">
                  {{ form.costPeriodStart }}-{{
                  form.costPeriodEnd
                  }}
                </td>
              </tr>
            </tbody>
          </table>
          <h3>四、非税信息</h3>
          <table class="table" border="1" cellspacing="0" cellpadding="15">
            <tbody>
              <tr>
                <th>业务单号</th>
                <td>{{ form.pnNum }}</td>
                <th>非税单号</th>
                <td>{{ form.payNoteNum }}</td>
              </tr>
              <tr></tr>
              <tr>
                <th align="center">发送状态</th>
                <td>{{ dictVal_sendStatus(form.sendStatus) }}</td>
                <th>票据编号</th>
                <td colspan="3">{{ form.pnReceiptNum }}</td>
              </tr>
              <tr></tr>
              <tr>
                <th align="center">付款时间</th>
                <td>{{ form.pnPaidDate }}</td>
                <th>银行名称</th>
                <td colspan="3">{{ form.pnBankName }}</td>
              </tr>
              <tr></tr>
              <tr>
                <th align="center">付款人</th>
                <td>{{ form.pnPayerName }}</td>
              </tr>
            </tbody>
          </table>
          <h3 v-if="type == 'edit'">上传文件</h3>
          <h3 v-else>查看附件</h3>
          <v-upload
            v-if="dialogTableVisible"
            ref="upload"
            :busId="form.billId"
            modelType="financeAccounting"
            @onSuccess="onSuccess"
            v-model="uploadFileList"
            :isView="type === 'preview' || type == 'pay'|| type == 'review'"
          />
          <div>
            <h3 v-if="type !== 'edit'">操作记录</h3>
            <div v-if="type !== 'edit'">
              <approval-record style="margin-top: 20px;" v-for="(item, index) in recordingLlist" :key="index" v-bind="item" />
            </div>
            <h3 v-if="type == 'edit' || type == 'review' || type == 'pay'">办理意见</h3>
            <el-input
              v-if="type == 'edit' || type == 'review' || type == 'pay'"
              type="textarea"
              :rows="2"
              maxlength="100"
              placeholder="请输入意见..."
              v-model="form.opinion"
            />
          </div>
        </div>
        <el-divider></el-divider>
        <div style="overflow: hidden;">
          <el-button plain style="float: right;  " v-show="!notThrough||type == 'preview'" @click="prints">打印</el-button>
          <el-button plain style="float: right; margin-right: 10px; " v-if="type == 'review'" :disabled="!notThrough" v-throttle=" [()=>review('02')]">复核通过</el-button>
          <el-button plain style="float: right;  margin-right: 10px;" v-if="type == 'review'&&notThrough" v-throttle=" [()=>review('03')]">租金复核不通过并退回</el-button>
          <el-button type="primary" style="float: right;  " v-if="type == 'edit'" v-throttle="[generateBill]">生成租金账单</el-button>
          <el-button v-if="type == 'pay'" type="primary" v-throttle=" [()=>pay('02')]" style="float: right; margin-right: 10px;">确定</el-button>
          <el-button plain @click="dialogTableVisible = false" style="float: right; margin-right: 10px;">取消</el-button>
        </div>
      </div>
      <div style="display:none">
        <section ref="printTemplate" id="printTemplate">
          <h2 style="text-align: center; font-size: 24px; font-weight: 400;">福田物管中心租赁租金收款付明细表</h2>
          <div class="template-head">
            <div class="template-head-font">单位名称:福田区物业管理中心</div>
          </div>
          <div class="table-div">
            <table class="table table-bordered" cellspacing="0">
              <thead class="thead-light"></thead>
              <tbody>
                <tr>
                  <th rowspan="11">物业租金支付明细</th>
                  <th>收款单位名称</th>
                  <td colspan="5">{{ form.rentContract.customerName }}</td>
                </tr>
                <tr>
                  <th>面积(m²)</th>
                  <td colspan="5">{{ form.rentContract.buildingArea }}</td>
                </tr>
                <tr>
                  <th>月租金(元)</th>
                  <td colspan="5">{{ form.rentContract.rentAmount }}</td>
                </tr>
                <tr>
                  <th>合同期限</th>
                  <td colspan="5">{{ form.rentContract.startDate }}-{{ form.rentContract.endDate }}</td>
                </tr>
                <tr>
                  <th>合同总租金(元)</th>
                  <td colspan="5">{{form.contractReceivableMoneyTotal}}</td>
                </tr>
                <tr>
                  <th>合同累计已付金额(元)</th>
                  <td colspan="5">{{form.contractActualMoneyTotal}}</td>
                </tr>
                <tr>
                  <th>本次申请付款金额(元)</th>
                  <td colspan="5">{{form.receivableTotal}}</td>
                </tr>
                <tr>
                  <th>本次申请付款金额期间</th>
                  <td colspan="5">{{form.costPeriodStart}}-{{form.costPeriodEnd}}</td>
                </tr>
                <tr>
                  <th>合同租金余款(元)</th>
                  <td colspan="5">{{form.contractArrearsTotal}}</td>
                </tr>
                <tr>
                  <th>制表人</th>
                  <td colspan="2">{{form.createName}}</td>
                  <th align="center">日期</th>
                  <td colspan="2">{{form.createTime}}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </section>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import approvalRecord from '@/components/approval-record'
import uploadMedia from '@/components/upload-media'
import printJS from 'print-js'

import {
  billInitialization,
  generateBill,
  viewBill,
  getApprovalRecord,
} from '@/views/wy-finance/bill/api/accounting.js'

import { pay, approve } from '@/views/wy-finance/bill/api/rentReview'
import { getDict } from '~/utils'

export default {
  components: {
    uploadMedia,
    approvalRecord,
  },
  data () {
    return {
      reviewLoading: false,
      notThrough: true,
      multipleSelection: [],
      dialogTitle: '',
      recordingLlist: [],
      type: '',
      form: {
        rentContract: {
          customerName: '',
        },
        receivables: {
          receivableTotal: '',
          currentContractReceivableMoney: '',
        },
      },
      // 合同
      rentContractId: '',
      uploadFileList: [],
      type: 'add', //弹窗类型，默认新增
      dialogTableVisible: false,
    }
  },
  watch: {
    'form.collectionBillDetails': {
      handler (val, oldVal) {
        if (this.type == 'edit') {
          this.form.receivableTotal = 0
          this.form.currentContractReceivableMoney = 0
          this.form.currentReceivableMoney = 0
          this.form.currentAdjustmentMoney = 0
          val.forEach((e) => {
            if (e.checked) {
              this.form.currentContractReceivableMoney += e.receivableMoneyOld
              this.form.currentReceivableMoney += e.arrears
              this.form.currentAdjustmentMoney += e.adjustmentAmount
              this.form.receivableTotal += e.billAmount
            }
          })
          var newArray = this.form.collectionBillDetails.filter((e) => {
            return e.checked
          })
          if (newArray.length > 0) {
            this.form.costPeriodStart = newArray[0].costPeriodStart
            const index = newArray.length - 1
            this.form.costPeriodEnd = newArray[index].costPeriodEnd
          } else {
            this.form.costPeriodStart = ''
            this.form.costPeriodEnd = ''
          }
        }
      },
      deep: true,
    },
  },

  methods: {
    CheckApplicationAmount () {
      const result = this.form.collectionBillDetails.some((item) => {
        return item.billAmount > 0 && item.billAmount <= item.arrears
      })
      !result &&
        this.$message({
          message: '本次申请收款金额不得为负数或大于待收金额',
          type: 'warning',
        })
      return result
    },
    //   打印事件
    prints () {
      printJS({
        printable: 'printTemplate',
        type: 'html',
        frameId: 'printFrame',
        style: this.getPrintStyle(),
        scanStyles: false, //扫描页面样式
        targetStyles: ['*'],
      })
    },
    // 打印所需样式
    getPrintStyle () {
      return `
               .table > tbody > tr > td,
               .table > tbody > tr > th,
               .table > tfoot > tr > td,
               .table > tfoot > tr > th,
               .table > thead > tr > td,
               .table > thead > tr > th {
                 padding: 0.785rem 1rem;
                 height: 44px;
                 border: 1px solid black;
               }
               th{
                 font-weight: 400;
    
               }
                 `
    },
    //    码值转换
    dictVal_sendStatus (cellValue) {
      if (!cellValue) return
      let obj = getDict('send_status').find((p) => p.value == cellValue)
      return obj ? obj.label : ''
    },
    // 收款明细勾选全部
    handleSelectionChange (val) {
      if (this.type == 'edit') {
        this.multipleSelection = val
        this.form.collectionBillDetails.forEach((e, i) => {
          this.form.collectionBillDetails[i].checked =
            this.multipleSelection.length > 0
        })
      }
    },
    check (s, v) {
      if (s.length > 0) {
        this.$nextTick(() => {
          this.form.costPeriodStart = s[0].costPeriodStart
          const index = s.length - 1
          this.form.costPeriodEnd = s[index].costPeriodEnd
        })
      }
    },
    // 打开弹框
    show (type, item) {
      this.dialogTableVisible = true
      this.type = type
      this.notThrough = true,
        this.form.billId = item.billId
      this.rentContractId = item.rentContractId
      switch (type) {
        case 'preview':
        case 'review':
        case 'pay':
          this.viewBill(item.billId)
          this.approvalRecord(item.billId)
          break
        case 'edit':
          this.$nextTick(() => {
            this.billInitialization(item.rentContractId)
          })
          break
      }
    },
    //支付
    async pay (approvalResult) {
      const res = await pay({
        approvalResult,
        busId: this.form.billId,
        opinion: this.form.opinion,
      })
      if (res.data.code == 0) {
        this.$message.success(res.data.msg)
        this.$emit('changeAccountList')
        this.dialogTableVisible = false
      }
    },
    // 复核
    async review (approvalResult) {
      this.reviewLoading = true
      const rps = await approve({
        approvalResult,
        busId: this.form.billId,
        opinion: this.form.opinion,
      })
      if (rps.data.code == 0) {
        this.$emit('changeAccountList')
        this.$message({
          message: '复核成功',
          type: 'success',
        })
        this.reviewLoading = false
        this.notThrough = false
      }
    },
    // 上传失败
    onError (err, file, fileList) {
      this.err('上传失败')
    },
    // 生成租金账单
    async generateBill () {
      if (this.form.collectionBillDetails.length > 0) {
        let arr = this.form.collectionBillDetails.find((e) => {
          return e.checked
        })
        if (!arr)
          return this.$message({
            message: '请选择本次需要汇总的收款明细',
            type: 'warning',
          })
      } else
        return this.$message({
          message: '当前合同下暂无收款明细',
          type: 'warning',
        })
      //调用本次申请金额验证方法
      if (!this.CheckApplicationAmount()) return
      if (this.uploadFileList.length)
        this.$refs.upload.submit('accounting', this.form.billId)
      else {
        const res = await generateBill(this.form)
        if (res.data.code == 0) {
          this.$message.success(`生成租金账单成功!`)
          this.$emit('changeAccountList', this.rentContractId)
          this.dialogTableVisible = false
        } else this.$message.error(res.data.msg)
      }
    },
    // 上传成功
    async onSuccess (response, file, fileList) {
      this.form.billId = response.data
      const res = await generateBill(this.form)
      if (res.data.code == 0) {
        this.$emit('changeAccountList', this.rentContractId)
        this.dialogTableVisible = false
      } else this.$message.error(res.data.msg)
    },
    //获取审批列表
    async approvalRecord (id) {
      const res = await getApprovalRecord(id)
      if (res.data.code == 0) this.recordingLlist = res.data.data
    },
    //编辑获取初始化租金账单
    async billInitialization (id) {
      const rps = await billInitialization(id)
      this.form = rps.data.data
    },
    //复核生成账单初始化
    async viewBill (id) {
      const rps = await viewBill(id)
      this.form = rps.data.data
    },
  },
}
</script>
<style lang="scss" scoped>
h3 {
  margin: 30px 0;
}

.el-dialog__header {
  border: 1px solid #e3e3e3;
}

.table {
  border: 1px solid #f4f4f4;

  tr {
    th,
    td {
      border: 1px solid #f4f4f4;
      text-align: left;
    }
  }
}
</style>